//
//  SLRecordSegmentedControl.swift
//  sulit-loan
//
//  Created by 王刚锋 on 2025/4/17.
//  Copyright © 2025 coolBoy. All rights reserved.
//

import UIKit

class SLRecordSegmentedControl: UIView {
    
    // MARK: - Properties
    private var segments: [UIButton] = []
    private var titles: [String] = []
    private var selectedIndex: Int = 0
    
    // 外观配置
    private let segmentHeight: CGFloat = 32
    private let segmentCornerRadius: CGFloat = 10
    private let segmentSpacing: CGFloat = 0
    
    private let defaultTitleColor: UIColor = rgba(hex: "#8F8F8F")
    private let selectedTitleColor: UIColor = rgba(hex: "#1608EC")
    private let selectedBackgroundColor: UIColor = .white
    private let unselectedBackgroundColor: UIColor = .clear
    
    // 回调
    var onSegmentSelected: ((Int) -> Void)?
    
    // MARK: - Initialization
    init(titles: [String]) {
        self.titles = titles
        super.init(frame: .zero)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    lazy var backView:UIView = {
        let v = UIView()
        v.backgroundColor = rgba(hex: "#F3F6F9")
        v.layer.borderWidth = 1
        v.layer.cornerRadius = 14
        v.layer.borderColor = rgba(hex: "#DFE2E7").cgColor
        self.addSubview(v)
        v.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.height.equalTo(44)
            make.bottom.equalTo(0)
        }
        return v
    }()
    
    // MARK: - UI Setup
    private func setupUI() {
        backgroundColor = .clear
        
        // 创建分段按钮
        for (index, title) in titles.enumerated() {
            let button = UIButton(type: .custom)
            button.setTitle(title, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .medium)
            button.setTitleColor(rgba(hex: "#1608EC"), for: .selected)
            button.setTitleColor(rgba(hex: "#8F8F8F"), for: .normal)
            button.layer.cornerRadius = 10
            button.layer.borderWidth = 1
            button.layer.borderColor = rgba(hex: "#16498D", a: 0).cgColor
            button.tag = index
            button.addTarget(self, action: #selector(segmentTapped(_:)), for: .touchUpInside)
            
            segments.append(button)
            backView.addSubview(button)
        }
        
        // 默认选中第一个
        updateSegmentAppearance()
        
        // 使用 SnapKit 布局
        setupConstraints()
    }
    
    // MARK: - SnapKit 约束
    private func setupConstraints() {
        guard !segments.isEmpty else { return }
        
        // 第一个按钮约束
        segments[0].snp.makeConstraints { make in
            make.leading.equalTo(10)
            make.centerY.equalToSuperview()
            make.height.equalTo(segmentHeight)
        }
        
        // 中间按钮约束
        for i in 1..<segments.count {
            segments[i].snp.makeConstraints { make in
                make.leading.equalTo(segments[i-1].snp.trailing).offset(segmentSpacing)
                make.centerY.equalToSuperview()
                make.height.equalTo(segmentHeight)
                make.width.equalTo(segments[i-1].snp.width)
            }
        }
        
        // 最后一个按钮约束（确保整体居中）
        segments.last?.snp.makeConstraints { make in
            make.trailing.equalTo(-10)
        }
    }
    
    // MARK: - 更新选中状态
    private func updateSegmentAppearance() {
        for (index, button) in segments.enumerated() {
            let isSelected = (index == selectedIndex)
            button.backgroundColor = isSelected ? selectedBackgroundColor : unselectedBackgroundColor
            button.setTitleColor(isSelected ? selectedTitleColor : defaultTitleColor, for: .normal)
            button.layer.borderColor = isSelected ? rgba(hex: "#16498D", a: 0.12).cgColor : rgba(hex: "#16498D", a: 0).cgColor
        }
    }
    
    // MARK: - 点击事件
    @objc private func segmentTapped(_ sender: UIButton) {
        selectedIndex = sender.tag
        updateSegmentAppearance()
        onSegmentSelected?(selectedIndex)
    }
    
    // MARK: - 外部方法
    func setSelectedIndex(_ index: Int) {
        guard index >= 0 && index < segments.count else { return }
        selectedIndex = index
        updateSegmentAppearance()
    }
}
